package com.leedsoft.common;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by leeds on 2016/6/28 16:01.
 */
public class RequestUtil {
    private static final ThreadLocal<HttpServletRequest> requestThreadLocal = new ThreadLocal<>();
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = requestThreadLocal.get();
        Assert.notNull(request, "HttpServletRequest is null!");
        return request;
    }
    public static void init(HttpServletRequest request) {
        requestThreadLocal.set(request);
    }
    public static boolean isAjax() {
        HttpServletRequest request = getRequest();
        String accept = request.getHeader("accept");
        String requestWith = request.getHeader("X-Requested-With");
        if(StringUtils.isNotBlank(accept) && accept.indexOf("application/json")>-1
                || StringUtils.isNotBlank(requestWith) && requestWith.indexOf("XMLHttpRequest")>-1
                || request.getRequestURI().endsWith(".json")) {
            return true;
        }
        return false;
    }
}
